<template>
    <div class="app-container">
        <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
            <el-form-item label="分组名称" prop="groupName">
                <el-input
                    v-model="queryParams.groupName"
                    placeholder="请输入分组名称"
                    clearable
                    size="small"
                    @keyup.enter.native="handleQuery"
                />
            </el-form-item>

            <el-form-item>
                <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
                <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
            </el-form-item>
        </el-form>

        <el-row :gutter="10" class="mb8">
            <el-col :span="1.5">
                <el-button
                    type="primary"
                    plain
                    icon="el-icon-plus"
                    size="mini"
                    @click="handleAdd"
                    v-hasPermi="['equipment:group:add']"
                >新增
                </el-button>
            </el-col>
            <el-col :span="1.5">
                <el-button
                    type="success"
                    plain
                    icon="el-icon-edit"
                    size="mini"
                    :disabled="single"
                    @click="handleUpdate"
                    v-hasPermi="['equipment:group:edit']"
                >修改
                </el-button>
            </el-col>
            <el-col :span="1.5">
                <el-button
                    type="danger"
                    plain
                    icon="el-icon-delete"
                    size="mini"
                    :disabled="multiple"
                    @click="handleDelete"
                    v-hasPermi="['equipment:group:remove']"
                >删除
                </el-button>
            </el-col>
            <el-col :span="1.5">
                <el-button
                    type="warning"
                    plain
                    icon="el-icon-download"
                    size="mini"
                    @click="handleExport"
                    v-hasPermi="['equipment:group:export']"
                >导出
                </el-button>
            </el-col>
            <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>

        <el-table v-loading="loading" :data="groupList" @selection-change="handleSelectionChange">
            <el-table-column type="selection" width="55" align="center"/>

            <el-table-column label="分组名称" align="center" prop="groupName"/>
            <el-table-column label="排序" align="center" prop="orderNum"/>
            <el-table-column label="备注" align="center" prop="remark"/>
            <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
                <template slot-scope="scope">
                    <el-button
                        size="mini"
                        type="text"
                        icon="el-icon-edit"
                        @click="handleUpdate(scope.row)"
                        v-hasPermi="['equipment:group:edit']"
                    >修改
                    </el-button>
                    <el-button
                        size="mini"
                        type="text"
                        icon="el-icon-delete"
                        @click="handleDelete(scope.row)"
                        v-hasPermi="['equipment:group:remove']"
                    >删除
                    </el-button>
                </template>
            </el-table-column>
        </el-table>

        <pagination
            v-show="total>0"
            :total="total"
            :page.sync="queryParams.pageNum"
            :limit.sync="queryParams.pageSize"
            @pagination="getList"
        />

        <!-- 添加或修改group对话框 -->
        <el-dialog :title="title" :visible.sync="open" width="700px" append-to-body>
            <el-form ref="form" :model="form" :rules="rules" label-width="80px">
                <el-form-item label="分组名称" prop="groupName">
                    <el-input v-model="form.groupName" placeholder="请输入分组名称"/>
                </el-form-item>
                <el-form-item label="排序" prop="orderNum">
                    <el-input v-model="form.orderNum"
                              placeholder="请选择排序"
                              type="number"
                    />
                </el-form-item>
                <el-form-item label="备注" prop="remark">
                    <el-input v-model="form.remark" type="textarea" placeholder="请输入内容"/>
                </el-form-item>
            </el-form>

            <el-button @click="addSensor">添加信息点</el-button>

            <el-table :data="form.sensorList" :height="250">
                <el-table-column label="网关" align="center" prop="gatewayId">
                    <template slot-scope="scope">
                        <el-select v-model="scope.row.gatewayId"
                                   placeholder="选择网关"
                        >
                            <el-option
                                v-for="item in gatewayList"
                                :key="item.value"
                                :label="item.label"
                                :value="item.value"
                                @click.native="tableChangeGateway(item.value, scope.$index)"
                            />
                        </el-select>
                    </template>
                </el-table-column>

                <el-table-column label="信息点" align="center" prop="sensorId">
                    <template slot-scope="scope">
                        <el-select v-model="scope.row.sensorId"
                                   placeholder="选择信息点"
                        >
                            <el-option
                                v-for="item in scope.row.sensorList"
                                :key="item.value"
                                :label="item.label"
                                :value="item.value"
                            />
                        </el-select>
                    </template>
                </el-table-column>

                <!--        <el-table-column label="图标" align="center" prop="icon">-->
                <!--          <template slot-scope="scope">-->
                <!--            <image-preview :key="scope.$index" :src="scope.row.icon" :width="50" :height="50"/>-->
                <!--          </template>-->
                <!--        </el-table-column>-->

                <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
                    <template slot-scope="scope">
                        <!--            <el-link type="primary" :underline="false" @click="showChooseIcon(scope.row, scope.$index)">选择图标</el-link>-->
                        <el-link style="margin-left: 5px" type="danger" :underline="false"
                                 @click="deleteSensor(scope.row, scope.$index)"
                        >删除
                        </el-link>
                    </template>
                </el-table-column>

            </el-table>

            <div slot="footer" class="dialog-footer">
                <el-button type="primary" @click="submitForm">确 定</el-button>
                <el-button @click="cancel">取 消</el-button>
            </div>

        </el-dialog>


        <!--    <el-dialog title="选择图标" :visible.sync="open2" width="500px" append-to-body>-->
        <!--      <el-tabs v-model="activeName" @tab-click="handleClick">-->
        <!--        <el-tab-pane label="系统图标" name="system">-->
        <!--          <el-row>-->
        <!--            <el-col :span="6" v-for="(item, index) in iconList">-->
        <!--              <div>-->
        <!--                <div style="display: flex; flex-flow: column">-->
        <!--                  <image-preview :key="item.id" :src="item.url" :width="100" :height="100"/>-->
        <!--                  <div style="width: 100px; display: flex; justify-content: space-between; padding-top: 10px">-->
        <!--                    <el-link type="info" :underline="false">{{ item.name }}</el-link>-->
        <!--                    <el-link v-if="item.url===icon" type="primary" :underline="false" @click="unChooseIcon">取消选择-->
        <!--                    </el-link>-->
        <!--                    <el-link v-else type="primary" :underline="false" @click="chooseIcon(item.url)">选择</el-link>-->
        <!--                  </div>-->
        <!--                </div>-->
        <!--              </div>-->
        <!--            </el-col>-->
        <!--          </el-row>-->
        <!--        </el-tab-pane>-->

        <!--        <el-tab-pane label="自定义上传" name="custom">-->
        <!--          <el-form label-width="80px">-->
        <!--            <el-form-item label="上传图标">-->
        <!--              <image-upload :limit="1" :file-size="5" v-model="icon"/>-->
        <!--            </el-form-item>-->
        <!--          </el-form>-->
        <!--        </el-tab-pane>-->

        <!--      </el-tabs>-->

        <!--      <div slot="footer" class="dialog-footer">-->
        <!--        <el-button type="primary" @click="submitIcon">确 定</el-button>-->
        <!--        <el-button @click="cancelIcon">取 消</el-button>-->
        <!--      </div>-->

        <!--    </el-dialog>-->

    </div>
</template>

<script>
import { listGroup, getGroup, delGroup, addGroup, updateGroup } from '@/api/equipment/group'
import { listSelect } from '@/api/equipment/gateway'
import { listSensorByGatewayId } from '@/api/equipment/sensor'
import { listSensorType } from '@/api/system/sensorType'
import { listIcon } from '@/api/biz/icon'

export default {
    name: 'Group',
    data() {
        return {
            // 遮罩层
            loading: true,
            // 选中数组
            ids: [],
            // 非单个禁用
            single: true,
            // 非多个禁用
            multiple: true,
            // 显示搜索条件
            showSearch: true,
            // 总条数
            total: 0,
            // group表格数据
            groupList: [],
            // 弹出层标题
            title: '',
            // 是否显示弹出层
            open: false,
            // 查询参数
            queryParams: {
                pageNum: 1,
                pageSize: 10,
                groupName: null,
                orderNum: null,
                projectId: null
            },
            // 表单参数
            form: {},
            // 表单校验
            rules: {
                groupName: [
                    { required: true, message: '请输入分组名称', trigger: 'blur' }
                ],
                orderNum: [
                    { required: true, message: '请选择排序', trigger: 'blur' }
                ]
            },
            gatewayList: [],
            sensorTypeList: [],
            iconList: [],
            open2: false,
            activeName: 'system',
            index: null,
            icon: ''
        }
    },
    created() {
        this.getList()
        this.getGatewayList()
        // this.getSensorTypeList()
        this.getListIcon()
    },
    methods: {

        handleClick(tab, event) {
            this.icon = ''
        },

        addSensor() {
            let obj = {
                gatewayId: null,
                sensorList: []
                // icon: ''
            }
            this.form.sensorList.push(obj)
        },

        deleteSensor(row, index) {
            this.form.sensorList.splice(index, 1)
        },

        getListIcon() {
            listIcon().then(response => {
                this.iconList = []
                for (let i = 0; i < response.data.length; ++i) {
                    let obj = {}
                    obj['id'] = response.data[i]['id']
                    obj['name'] = response.data[i]['name']
                    obj['url'] = response.data[i]['url']
                    this.iconList.push(obj)
                }
            })
        },

        getSensorTypeList() {
            this.sensorTypeList = []
            listSensorType().then(response => {
                // console.log(response)
                for (let item of response.data) {
                    if (item.parentId === 0) {
                        let level1 = {
                            value: item.id,
                            label: item.typeName,
                            children: []
                        }
                        this.sensorTypeList.push(level1)
                    }
                }

                for (let item of response.data) {
                    let obj = this.sensorTypeList.find((level1) => {
                        return level1.value === item.parentId
                    })
                    if (obj !== undefined) {
                        let level2 = {
                            value: item.id,
                            label: item.typeName
                        }
                        obj.children.push(level2)
                    }
                }

            })
        },
        tableChangeGateway(gatewayId, index) {
            listSensorByGatewayId(gatewayId).then(response => {
                let arr = []
                for (let i = 0; i < response.data.length; ++i) {
                    let obj = {}
                    obj['value'] = response.data[i]['sensorId']
                    obj['label'] = response.data[i]['sensorName']
                    arr.push(obj)
                }
                this.form.sensorList[index]['sensorList'] = arr
            })
        },
        showChooseIcon(row, index) {
            this.index = index
            this.icon = row.icon
            this.open2 = true
        },
        chooseIcon(url) {
            this.icon = url
        },
        unChooseIcon() {
            this.icon = ''
        },
        submitIcon() {
            this.form.sensorList[this.index]['icon'] = this.icon
            this.index = null
            this.icon = ''
            this.open2 = false
        },
        cancelIcon() {
            this.index = null
            this.icon = ''
            this.open2 = false
        },
        getGatewayList() {

            listSelect().then(response => {
                this.gatewayList = []

                for (let item of response.data) {
                    let temp = {}
                    temp['value'] = item.gatewayId
                    temp['label'] = item.gatewayName
                    temp['serverOnline'] = item.serverOnline
                    this.gatewayList.push(temp)
                }
            })
        },

        getList() {
            this.loading = true
            listGroup(this.queryParams).then(response => {
                this.groupList = response.rows
                this.total = response.total
                this.loading = false
            })
        },

        cancel() {
            this.open = false
            this.reset()
        },

        reset() {
            this.form = {
                id: null,
                groupName: null,
                orderNum: 1,
                projectId: null,
                sensorList: [],
                createBy: null,
                createTime: null,
                updateBy: null,
                updateTime: null,
                remark: null
            }
            this.resetForm('form')
        },

        handleQuery() {
            this.queryParams.pageNum = 1
            this.getList()
        },

        resetQuery() {
            this.resetForm('queryForm')
            this.handleQuery()
        },

        handleSelectionChange(selection) {
            this.ids = selection.map(item => item.id)
            this.single = selection.length !== 1
            this.multiple = !selection.length
        },

        handleAdd() {
            this.reset()
            this.open = true
            this.title = '添加分组'
        },

        handleUpdate(row) {
            this.reset()
            const id = row.id || this.ids
            getGroup(id).then(response => {
                this.form = response.data
                this.open = true
                this.title = '修改分组'
            })
        },

        submitForm() {
            this.$refs['form'].validate(valid => {
                if (valid) {
                    if (this.form.id != null) {
                        updateGroup(this.form).then(response => {
                            this.$modal.msgSuccess('修改成功')
                            this.open = false
                            this.getList()
                        })
                    } else {
                        addGroup(this.form).then(response => {
                            this.$modal.msgSuccess('新增成功')
                            this.open = false
                            this.getList()
                        })
                    }
                }
            })
        },

        handleDelete(row) {
            const ids = row.id || this.ids
            this.$modal.confirm('是否确认删除group编号为"' + ids + '"的数据项？').then(function() {
                return delGroup(ids)
            }).then(() => {
                this.getList()
                this.$modal.msgSuccess('删除成功')
            }).catch(() => {
            })
        },

        handleExport() {
            this.download('equipment/group/export', {
                ...this.queryParams
            }, `group_${new Date().getTime()}.xlsx`)
        }
    }
}
</script>
